package cn.dida.controller;

import cn.dida.exception.BizzException;
import cn.dida.model.*;
import cn.dida.service.LgsDepotService;
import cn.dida.service.LgsPdaUserService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;
import cn.dida.util.ValidUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by zhangzhiling on 2017/2/8.
 */
@Controller
@RequestMapping("/pdaUser")
public class LgsPdaUserController extends BaseController {

    @Autowired
    private LgsPdaUserService lgsPdaUserService;

    @Autowired
    private LgsDepotService lgsDepotService;

    /**
     * 获取pad用户列表
     * @param request
     * @param keyword
     * @param sta
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/list")
    public ModelAndView getList(HttpServletRequest request, String keyword,String realName,String depotName, Integer sta, Integer page) throws Exception{

        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);
        Integer companyId = userSession.getCompanyId();

        Pageable<LgsPdaUser> list = lgsPdaUserService.getList(companyId,keyword,realName,depotName,sta,page);
        List<LgsDepot> depotList = lgsDepotService.getList(companyId, 1);
        List<LgsNode> nodeList = lgsPdaUserService.getNodeList(companyId,1);
        model.put("nodeList", nodeList);
        model.put("pdaUserList", list);
        model.put("depotList", depotList);
        model.put("keyword", keyword);
        model.put("realName", realName);
        model.put("depotName", depotName);
        model.put("sta", sta);
        return new ModelAndView("lgs_pda_user").addAllObjects(model);
    }

    /**
     * 添加新的pad用户
     * @param request
     * @param lgsPdaUser
     * @return
     */
    @ResponseBody
    @PostMapping("/insert")
    public HttpResponseBodyWrapper setPdaUser(HttpServletRequest request, @RequestBody LgsPdaUser lgsPdaUser){

        lgsPdaUser.setAccount(StringUtils.trimToNull(lgsPdaUser.getAccount()));
        lgsPdaUser.setPwd(StringUtils.trimToNull(lgsPdaUser.getPwd()));
        lgsPdaUser.setConfirmPwd(StringUtils.trimToNull(lgsPdaUser.getConfirmPwd()));
        lgsPdaUser.setRealName(StringUtils.trimToNull(lgsPdaUser.getRealName()));
        lgsPdaUser.setSta(lgsPdaUser.getSta() == null ? 1 : lgsPdaUser.getSta());
        lgsPdaUser.setNodes(StringUtils.trimToNull(lgsPdaUser.getNodes()));

        if(lgsPdaUser.getAccount() == null){
            throw new BizzException(BizzException.error_code_invalid_params, "请输入用户名！");
        }
        if (!Pattern.matches(ValidUtil.WENZI_PATTERN,lgsPdaUser.getAccount())) {
            throw new BizzException(BizzException.error_code_invalid_params, "用户名仅限汉字、数字、字母！");
        }
        if(lgsPdaUser.getPwd() == null || lgsPdaUser.getPwd().length()<6 || !Pattern.matches(ValidUtil.PWS_PATTERN,lgsPdaUser.getPwd())){
            throw new BizzException(BizzException.error_code_invalid_params, "密码格式不正确！");
        }
        if(!lgsPdaUser.getPwd().equals(lgsPdaUser.getConfirmPwd()) ){
            throw new BizzException(BizzException.error_code_invalid_params, "两次密码输入不同！");
        }
        if(lgsPdaUser.getRealName() == null){
            throw new BizzException(BizzException.error_code_invalid_params, "请输入操作人！");
        }
        if (!Pattern.matches(ValidUtil.WENZI_PATTERN,lgsPdaUser.getRealName())) {
            throw new BizzException(BizzException.error_code_invalid_params, "操作人仅限汉字、数字、字母！");
        }
        if(lgsPdaUser.getDepotId() == null){
            throw new BizzException(BizzException.error_code_invalid_params, "请选择节点！");
        }
        if(lgsPdaUser.getNodes() == null){
            throw new BizzException(BizzException.error_code_invalid_params, "请选择操作类型！");
        }
        if(lgsPdaUserService.testAccount(lgsPdaUser.getAccount())){
            throw new BizzException(BizzException.error_code_invalid_params, "用户名已存在！");
         }
        UserSession userSession = getUserSession(request);
        lgsPdaUser.setcAdmin(userSession.getId_admin());
        lgsPdaUser.setCompanyId(userSession.getCompanyId());

        Boolean result = lgsPdaUserService.insert(lgsPdaUser);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 根据id获取pad详情
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("/getUser/{id}")
    public HttpResponseBodyWrapper getLgsDepot(@PathVariable Integer id){

        Map<String, Object> map = new HashMap<>();
        LgsPdaUser lgsPdaUser = lgsPdaUserService.getPdaUser(id);
        map.put("lgsPdaUser",lgsPdaUser);
        List<Map<String, Object>> nodeList = lgsPdaUserService.getNodeByUser(id);
        map.put("nodeList", nodeList);
        return new HttpResponseBodyWrapper(map);
    }

    /**
     * 提交跟新pad用户信息
     * @param request
     * @param lgsPdaUser
     * @return
     */
    @ResponseBody
    @PostMapping("/update")
    public HttpResponseBodyWrapper update(HttpServletRequest request, @RequestBody LgsPdaUser lgsPdaUser){

        lgsPdaUser.setPwd(StringUtils.trimToNull(lgsPdaUser.getPwd()));
        lgsPdaUser.setConfirmPwd(StringUtils.trimToNull(lgsPdaUser.getConfirmPwd()));
        lgsPdaUser.setSta(lgsPdaUser.getSta() == null ? 1 : lgsPdaUser.getSta());
        lgsPdaUser.setNodes(StringUtils.trimToNull(lgsPdaUser.getNodes()));

        String pwd = lgsPdaUser.getPwd();
        String confirmPwd = lgsPdaUser.getConfirmPwd();
        if(confirmPwd != null && pwd != null){

            if(lgsPdaUser.getPwd() == null || lgsPdaUser.getPwd().length()<6 || !Pattern.matches(ValidUtil.PWS_PATTERN,lgsPdaUser.getPwd())){
                throw new BizzException(BizzException.error_code_invalid_params, "密码格式不正确！");
            }
            if(!lgsPdaUser.getPwd().equals(lgsPdaUser.getConfirmPwd())){
                throw new BizzException(BizzException.error_code_invalid_params, "两次密码输入不同！");
            }
        }

        if(lgsPdaUser.getNodes() == null){
            throw new BizzException(BizzException.error_code_invalid_params, "请选择操作类型！");
        }
        Boolean result = lgsPdaUserService.update(lgsPdaUser);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 验证用户名（账户）是否已存在
     * @param account
     * @return
     */
    @ResponseBody
    @GetMapping("/test/{account}")
    public HttpResponseBodyWrapper testAccount(@PathVariable String account){
        Boolean result = lgsPdaUserService.testAccount(account);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 数据导出
     * @param request
     * @param response
     * @param keyword 查询条件
     * @param sta 状态：1使用中，2已停用
     * @return
     * @throws IOException
     */
    @GetMapping("/export")
    public String product_export(HttpServletRequest request, HttpServletResponse response, String keyword,String realName,String depotName, Integer sta) throws IOException {
        UserSession userSession = getUserSession(request);
        List<LgsPdaUser> exportList = lgsPdaUserService.queryForExport(userSession.getCompanyId(),keyword,realName,depotName,sta);

        String fileName = "PDA用户数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (LgsPdaUser user : exportList) {
            fmap = new HashMap<String, Object>();
            Long tid = NumberUtils.toLong(user.getId().toString(), 0L);
            fmap.put("id", tid);
            fmap.put("account", user.getAccount());

            fmap.put("depotName", user.getDepotName());

            fmap.put("realName", user.getRealName());
            fmap.put("cTime", DateUtils.formatTimeInMillis((Long)user.getcTime()));
            fmap.put("cAdmin", user.getcAdmin());
            if (user.getSta() == 1) {
                fmap.put("sta", "正常");
            } else if (user.getSta() == 0) {
                fmap.put("sta", "停用");
            }

            list.add(fmap);
        }

        String columnNames[] = {"ID", "用户名", "操作节点", "操作人", "录入时间", "录入人", "状态"};//列名
        String keys[] = {"id", "account", "depotName", "realName", "cTime", "cAdmin", "sta"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }
}
